package com.environment_pro.monitor.socket;

import java.util.Date;
import java.util.Scanner;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.environment_pro.monitor.model.TbDeviceLoad;
import com.environment_pro.monitor.service.TbDeviceLoadService;
import com.environment_pro.monitor.service.TbDeviceMsgService;

public class MinaBizHandler extends IoHandlerAdapter {

  public void exceptionCaught(IoSession session, Throwable cause)
      throws Exception {
    cause.printStackTrace();
  }

  @Override
  public void sessionCreated(IoSession session) throws Exception {
    // TODO Auto-generated method stub
    super.sessionCreated(session);
  }

  @Override
  public void sessionOpened(IoSession session) throws Exception {
    // TODO Auto-generated method stub
    super.sessionOpened(session);
  }

  @Override
  public void sessionClosed(IoSession session) throws Exception {
    // TODO Auto-generated method stub
    super.sessionClosed(session);
    session.close(true);
  }

  @Override
  public void sessionIdle(IoSession session, IdleStatus status)
      throws Exception {
    // TODO Auto-generated method stub
    System.out.println("IDLE : " + session.getIdleCount(status) + ">now : " + new Date());
  }

  @Override
  public void messageReceived(IoSession session, Object message)
      throws Exception {
    // TODO Auto-generated method stub
    String str = message.toString();
    System.out.println("Message received: " + str);
    TbDeviceMsgService tbDeviceMsgService = (TbDeviceMsgService) MinaServer.ctx.getBean("tbDeviceMsgService");
    tbDeviceMsgService.save(message.toString());
    session.write("ok");
    session.close(true);
    System.out.println("Message written !");

  }

  @Override
  public void messageSent(IoSession session, Object message) throws Exception {
    // TODO Auto-generated method stub
    super.messageSent(session, message);
    System.out.println("server sent : " + message.toString());
  }

  public static void main(String[] args) {
    // TODO Auto-generated method stub

  }

}